import { shenhePayment } from '@/services/order';
import { findMyParentList } from '@/services/users';
import {
  ModalForm,
  ProForm,
  ProFormList,
  ProFormMoney,
  ProFormText,
} from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Button, Form } from 'antd';
import React, { useState } from 'react';

interface Props {
  id?: number | undefined;
  row?: API.LoginLog | undefined;
  onSuccess: (event: boolean) => void;
}

const OrderShenhe: React.FC<Props> = (props) => {
  const { id, row, onSuccess } = props;
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm<API.SelectItemOrderParams>();
  const showModal = () => {
    // @ts-ignore
    fetchByUsersDetailList(row?.userId);
  };

  const handleOpen = () => {
    setIsModalOpen(true);
  };

  const { runAsync: fetchByUsersDetailList, data: dataList } = useRequest(
    findMyParentList,
    {
      debounceWait: 100,
      manual: true,
      onSuccess: function () {
        handleOpen();
      },
    },
  );

  return (
    <>
      <ModalForm<API.SelectItemOrderParams>
        form={form}
        trigger={<Button>手动</Button>}
        onOpenChange={(open) => {
          console.log('KKKKKKKKKKKKKKKKKKKKKKKKK', open);
          if (open) {
            console.log('KKKKKKKKKKKKKKKKKKKKKKKKK OPEN', row?.userId);
            fetchByUsersDetailList(row?.userId).then((res) => {
              console.log('KKKKKKKKKKKKKKKKKKKKKKKKK', res);
              // @ts-ignore
              form.setFieldValue({
                users: dataList,
              });
            });
          }
        }}
        width={500}
        title={row?.userName}
        initialValues={{
          users: dataList,
        }}
        onFinish={(formData) => {
          let users = formData?.users;
          console.log(formData);
          return new Promise((resolve, reject) => {
            shenhePayment(id, users)
              .then((res) => {
                console.log(res);
                if (res.success) {
                  onSuccess(res.success);
                  resolve(true);
                } else {
                  reject(false);
                }
              })
              .catch(() => {
                reject(false);
              });
          });
        }}
      >
        <ProFormList
          name="users"
          initialValue={dataList}
          creatorButtonProps={false}
          itemContainerRender={(doms) => {
            return <ProForm.Group>{doms}</ProForm.Group>;
          }}
        >
          {(f, index, action) => {
            return (
              <>
                <div style={{ width: '150px' }}>
                  <ProFormText name={'name'} readonly={true} />
                </div>
                <ProFormMoney name={'price'} />
              </>
            );
          }}
        </ProFormList>
      </ModalForm>
    </>
  );
};

export default OrderShenhe;
